const COLUMNS_PER_ROW = 5; // 每行显示3张图片
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
function mainWindowOnLoad(){
	var params = window.arguments[0];
	var imageNodes = params.imageNodes;
	displayImages(imageNodes);
}

function getImageSize(imageNode){
	var imageSrc = imageNode.src;
	
    //init cache session
    var cacheService = Cc["@mozilla.org/network/cache-service;1"].getService(Ci.nsICacheService);
    var httpCacheSession = cacheService.createSession("HTTP", Ci.nsICache.STORE_ANYWHERE, Ci.nsICache.STREAM_BASED);
    var url = imageNode.src;
    var cacheKey = url.replace(/#.*$/, "");
    
    var fileSize = null;
    try {
        // try to get from http cache, return nsICacheEntryDescriptor            
        var descriptor = httpCacheSession.openCacheEntry(cacheKey, Ci.nsICache.ACCESS_READ, false);
        if (descriptor) {
            fileSize = descriptor.dataSize;
            descriptor.close();
        }
    } catch (ex) {
        if (ex.result == 0x804B003D) {            
          
        } else if (ex.result == 0x804b0040) {
           
        } else {
        	
        }
        return 0;
    }
    
    if (fileSize > 0) {
       return  fileSize;
    }else{
       return 0;
    }
        
		
}
function displayImages(imageNodes){
	imageNodes = imageNodes || [];
	var cols = 0, row, image, hbox, checkbox;
	var rows = document.getElementById("imagesContainer");
	for ( var i = 0, n = imageNodes.length; i < n; i++)
	{
		var imageNode = imageNodes[i];
		var imageSrc = imageNode.src;
//		if (imageSrc.toLowerCase().indexOf(".jpg")!=-1||imageSrc.toLowerCase().indexOf(".png")!=-1||imageSrc.toLowerCase().indexOf(".jpeg")!=-1||imageSrc.toLowerCase().indexOf(".gif")!=-1)
//		{
//			
//		}else{
//			continue;
//		}

        var fileSize = getImageSize(imageNode);
        fileSize = parseInt(fileSize/1024*100)/100;
        if(fileSize<2){
        	continue;
        }
		if (cols%COLUMNS_PER_ROW==0)
		{
			row = document.createElementNS(XUL_NS,"row"); // 开始新的一行
			row.setAttribute("align","center");			
			cols = 0;
		} 
		
		hbox = document.createElementNS(XUL_NS,"vbox");
		hbox.setAttribute("class", "image-cell");
		hbox.setAttribute("align", "center");
		hbox.setAttribute("style","padding:5px 5px 5px 5px;");
		image = document.createElementNS(XUL_NS,"image");// 创建 XUL
		// 图像元素来显示图片
		image.setAttribute("src",imageSrc);			// 图像元素来显示图片
		
		var additionalLabel = document.createElementNS(XUL_NS, "label");
        additionalLabel.setAttribute("value", imageNode.width+"x"+imageNode.height+"    "+fileSize+"KB");
		var base = 130;
        var w = imageNode.width;
        var h = imageNode.height;
        if(w>h){
        	width = base;
        	height = width*h/w ;
        }else{
        	height = base;
        	width = height*w/h;
        }
        width = width>base?base:width;
        height = height>base?base:height;
    	var mtop = parseInt((base-height)/2);
    	var mleft = parseInt((base-width)/2);
    		
		image.setAttribute("style","width:"+width+"px;height:"+height+"px;margin-top:"+mtop+"px;margin-left:"+mleft+"px;");			
		checkbox = document.createElementNS(XUL_NS,"checkbox");// 创建 XUL
																// 复选框元素以供用户选择
		checkbox.setAttribute("imageUrl",imageSrc);
		checkbox.setAttribute("label","选择");
		hbox.appendChild(image);
		hbox.appendChild(additionalLabel);
		hbox.appendChild(checkbox);
		row.appendChild(hbox);
		cols++;
		if ((cols %COLUMNS_PER_ROW==0&&cols!=0)||i==n-1)
		{
			rows.appendChild(row);
		}
		
	}
}
var saveDirectory = getDefaultSaveDirectory();
function selectSaveDirectory(){
	const	nsIFilePicker = Components.interfaces.nsIFilePicker;
	var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
	fp.init(window,"",nsIFilePicker.modeGetFolder);
	var result = fp.show(); // 显示目录选择对话框
	if (result == nsIFilePicker.returnOK)
	{
		var file = fp.file;
		saveDirectory = file;
		document.getElementById("mainWindow-save-path").value = file.path;// 把目录的路径显示在文本框中
	}
}

// 获得默认的图片保存目录，也就是当前用户的根目录
function getDefaultSaveDirectory(){
	var file = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("Home",Components.interfaces.nsIFile);
	return file;
}
function downloadSingleImage(uri,callback){
	var ios = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
	var imageURI = ios.newURI(uri,null,null); // 创建图像的 URI
	var imageFileName = uri.substring(uri.lastIndexOf("/") + 1);
	var channel = ios.newChannelFromURI(imageURI); // 创建读取 URI 指定的数据流的通道
	var observer = {
		onStreamComplete : function(loader,context,status,length,result){
			var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
			file.initWithFile(saveDirectory); // 图片保存的目录
			file.appendRelativePath(imageFileName);
			var stream = Components.classes["@mozilla.org/network/safe-file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
			stream.init(file,-1,-1,0);
			var bstream = Components.classes["@mozilla.org/binaryoutputstream;1"].createInstance(Components.interfaces.nsIBinaryOutputStream);
			bstream.setOutputStream(stream);
			bstream.writeByteArray(result,length); // 把图片流的全部字节写入输出文件流中
			if (stream instanceof Components.interfaces.nsISafeOutputStream)
			{
				stream.finish();
			} else
			{
				stream.close();
			}
			if (typeof callback == "function")
			{
				callback();
			}
		}
	};
	var streamLoader = Components.classes["@mozilla.org/network/stream-loader;1"].createInstance(Components.interfaces.nsIStreamLoader);
	streamLoader.init(channel,observer,null);
}

function download(){
	var rows = document.getElementById("imagesContainer");
	var checkboxes = rows.getElementsByTagName("checkbox");
	var imageUrls = [];
	for ( var i = 0, n = checkboxes.length; i < n; i++)
	{
		if (checkboxes[i].checked)
		{
			imageUrls.push(checkboxes[i].getAttribute("imageUrl")); // 用户选择的图片的
																	// URL
		}
	}
	var progressmeter = document.getElementById("downloadProgress");
	progressmeter.style.visibility = "visible";
	var total = imageUrls.length, step = 100 / total, current = 0;
	for ( var i = 0; i < total; i++)
	{
		downloadSingleImage(imageUrls[i],function(){
			var value = parseInt(progressmeter.value); // 更新进度条
			progressmeter.value = value + step;
		});
	}
	close();
}